#-*- coding: utf-8 -*-
'''
Created on 2016年8月4日

@author: huanghaoyu
'''

import xml.dom.minidom

class XmlUtils(object):
    '''
    XML parser and generator.
    '''
    
    @staticmethod
    def isFirstRequest(xml_str):
        dom_tree = xml.dom.minidom.parseString(xml_str)
        root = dom_tree.documentElement
        
        order_element = root.getElementsByTagName("order").item(0)
        
        if order_element is None:
            raise Exception("No order element.")
        
        if order_element.firstChild.nodeValue == '0':
            return True
        else:
            return False
    
    @staticmethod
    def getSessionId(xml_str):
        dom_tree = xml.dom.minidom.parseString(xml_str)
        root = dom_tree.documentElement
        
        session_id_elements = root.getElementsByTagName("sessionId");
        session_id = session_id_elements.item(0).firstChild.nodeValue
        return session_id
        
    @staticmethod
    def setSessionId(xml_str, session_id):
        dom_tree = xml.dom.minidom.parseString(xml_str)
        root = dom_tree.documentElement
        session_id_element = root.getElementsByTagName("sessionId").item(0)
        session_id_element.firstChild.nodeValue = session_id
        return dom_tree.toxml()
    
    @staticmethod
    def delTimestamp(xml_str):
        dom_tree = xml.dom.minidom.parseString(xml_str)
        root = dom_tree.documentElement
        timestamp_element = root.getElementsByTagName("timestamp").item(0)
        root.removeChild(timestamp_element)
        return dom_tree.toxml()
    
    @staticmethod
    def toXml(xml_str):
        dom_tree = xml.dom.minidom.parseString(xml_str)
        return dom_tree.toxml()
    
    @staticmethod
    def toPrettyXml(xml_str):
        dom_tree = xml.dom.minidom.parseString(xml_str)
        return dom_tree.toprettyxml()
            
